<template>
  <div class="create-user-panel">
    <!-- 新建账号 -->
    <div class="createUserPanel">
      <!-- start 新建账号 -->
      <div class="create-user-form" v-if="visible">
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-position="top"
          
          class="demo-ruleForm"
        >
          <el-form-item :label="$t('common.fields.employeeNumber.displayName')" prop="workNo">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              v-model="form.workNo"
              :placeholder="$t('common.fields.employeeNumber.placeholder')"
            ></el-input>
          </el-form-item>

          <el-form-item :label="$t('common.fields.fullName.displayName')" prop="displayName" >
            <input type="password" style="position: fixed;left: -9999px;" />
            <template v-if="isOpenData && form.staffId">
              <div class="open-data-input" v-show="!isShowInput" @click="showInput" style="cursor: pointer;">
                <open-data type="userName" :openid="form.staffId"></open-data>
              </div>
              <!-- 2022/05/23 解决线上bug（bugID=15570) 企微端的用户变更用户信息是需要置灰 -->
              <el-input
                v-show="isShowInput"
                v-model="form.displayName"
                :maxlength="50"
                :placeholder="$t('common.fields.fullName.placeholder')"
                disabled
              ></el-input>
            </template>
            <template v-else>
              <el-input
                v-model="form.displayName"
                :maxlength="50"
                :placeholder="$t('common.fields.fullName.placeholder')"
              ></el-input>
            </template>
          </el-form-item>

          <el-form-item :label="$t('common.fields.loginAccount.displayName')" prop="loginName" v-if="tenantType == 1">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              :disabled="Boolean(form.userId)"
              v-model="form.loginName"
              :placeholder="Boolean(form.userId) ? '' : $t('common.fields.loginAccount.placeholder2')"
            ></el-input>
          </el-form-item>
          <!-- 账号类型 -->
          <el-form-item v-if="accountInfo.showField" :label="$t('common.account.accountType')" prop="accountType">
            <el-tooltip :disabled="accountInfo.canEdit" :content="$t('common.account.switchAccountCount')">
              <el-radio-group v-model="form.accountType" :disabled="!accountInfo.canEdit">
                <el-radio :label="0" >{{$t('common.account.commonAccountType')}}</el-radio>
                <el-tooltip :disabled="Boolean(accountInfo.remainingCount)" :content="$t('common.account.insufficientAccount')">
                  <el-radio :label="1" :disabled="!accountInfo.remainingCount">{{$t('common.account.internalAccountType')}}</el-radio>
                </el-tooltip>
              </el-radio-group>
            </el-tooltip>
          </el-form-item>

          <el-form-item :label="$t('common.fields.loginPassword.displayName')" prop="pass" v-if="tenantType == 1" style="margin-bottom:22px;">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              :disabled="Boolean(form.userId)"
              type="password"
              show-password
              v-model="form.pass"
              :placeholder="Boolean(form.userId) ? '' : $t('common.fields.loginPassword.placeholder')"
            ></el-input>
          </el-form-item>

          <el-form-item :label="$t('common.fields.confirmPassword.displayName')" prop="checkPass" v-if="tenantType == 1">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              :disabled="Boolean(form.userId)"
              type="password"
              show-password
              v-model="form.checkPass"
              :placeholder="Boolean(form.userId) ? '' : $t('common.fields.confirmPassword.placeholder')"
            ></el-input>
          </el-form-item>

          <el-form-item :label="$t('common.fields.department.displayName')" prop="tagList">
            <biz-team-select
              :value="form.tagList"
              :type-service-provider="typeServiceProvider"
              collapse
              multiple
              @input="update"
              :fetch-func="getTagTreeByUser"
            />
          </el-form-item>

          <el-form-item :label="$t('common.fields.role.displayName')" prop="role">
            <div>
              <biz-role-select
                v-model="form.role"
                multiple
                :roles="roleOptions"
                :placeholder="$t('common.base.pleaseSelect')"
                @change="roleChange"
              />
              <!-- <el-select
                v-model="form.role"
                :placeholder="$t('common.base.pleaseSelect')"
                multiple
                @change="roleChange"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select> -->
            </div>
          </el-form-item>
          <!-- 更多角色选择 -->
          <el-form-item v-if="isService && !isProviderSign">
            <el-checkbox @change="getRoleList" v-model="isChecked">{{$t('common.fields.moreRole.displayName')}}</el-checkbox>

            <p v-if="isService && isChecked" class="warning-txt">
              {{$t('common.fields.moreRole.placeholder')}}
            </p>
          </el-form-item>

          <el-form-item :label="$t('common.fields.contactNumber.displayName')" prop="cellPhone">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              v-model="form.cellPhone"
              :placeholder="$t('common.placeholder.inputContactPhone')"
              @input="updateCellPhone"
            ></el-input>
          </el-form-item>

          <el-form-item :label="$t('common.fields.weChatId.displayName')" prop="wechat">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              v-model="form.wechat"
              :placeholder="$t('common.placeholder.inputWeChatAccount')"
            ></el-input>
          </el-form-item>

          <el-form-item :label="$t('common.fields.email.displayName')" prop="email" v-if="_isShowEmail">
            <input type="password" style="position: fixed;left: -9999px;" />
            <el-input
              v-model="form.email"
              :placeholder="$t('common.placeholder.inputEmail')"
            ></el-input>
          </el-form-item>

          <el-form-item :label="$t('common.fields.tags.displayName')" prop="labelList">
            <el-select
              v-if="labelList.length > 0"
              v-model="form.labelList"
              :placeholder="$t('common.base.pleaseSelect')"
              multiple
            >
              <el-option
                v-for="item in labelList"
                :key="item.id"
                :label="item.tagName"
                :value="item.id"
              >
              </el-option>
            </el-select>

            <div class="label-txt" v-else>
              {{$t('department.createUserPanel.noTags')}}
            </div>
          </el-form-item>

          <el-form-item v-if="!hiddencertificateList" :label="$t('common.fields.skillsCertificate.displayName')" prop="certificateList">
            <base-upload
              :value="form.certificateList"
              @input="upload"
              @remove="remove"
            ></base-upload>
          </el-form-item>
        </el-form>
      </div>
      <!-- end 编辑表单 -->
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
/* apis */
import {
  userLoginNameUnique,
  userWorkNoUnique,
  getBaseLabelList,
  getTagTreeByUser
} from '@src/api/DepartmentApi';
import { roleGetRoleTreeByUser } from '@src/api/RoleApi';
import { providerRole, getRoleTree } from '@src/api/serviceProviderApi';
import * as TeamApi from '@src/api/TeamApi'

/* util */
import { PHONE_REG } from '@src/util/validator';
import _ from 'lodash';
import { getRootWindowInitData } from '@src/util/window'

import { ValidatePassWordReg } from '@src/model/const/Reg'
import { PASS_WORD_MESSAGE } from '@src/model/const/Alert'
import { phoneNumberFilter } from '@src/util/format/string.ts';
/** mixin */
import { VersionControlOtherMixin } from '@src/mixins/versionControlMixin'

const rootWindowInitData = getRootWindowInitData()
// 邮箱格式正则 可以校验''firstname+lastname@example.com'这样特殊格式邮箱
const EMAIL_REG = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
import { validatePhone } from '@src/util/validator'
export default {
  name: 'create-user-panel',
  mixins: [VersionControlOtherMixin],
  inject: ['initData'],
  props: {
    accountInfo: {
      type: Object,
      default: () => ({})
    },
    userRow: {
      type: String
    },
    keyFrom:{
      type:String
    },
    typeServiceProvider: {
      type:String | Number,
      default: 0
    },
    hiddencertificateList: {
      type:Boolean,
      default: true
    },
  },
  watch: {
    'userRow':function(n,o) {
      if (n) {
        this.setForm(n);

        if(this.isRole){
          this.getRoleTreeByUser();
        }
      } else {
        this.initForm();
      }
      this.isShowInput = false
    },
  },
  data() {
    let validatePass = (rule, value, callback) => {
      if (!value && !this.form.userId) {
        callback(new Error(this.$t('common.base.inputPassword')));
      } else {
        
        if (this.form.checkPass !== '' && !this.form.userId) {
          this.$refs.form.validateField('checkPass');
        }
        
        if (value) {
          if (ValidatePassWordReg.test(value)) {
            callback();
          } else {
            callback(new Error(PASS_WORD_MESSAGE));
          }
        }
        
        callback();
      }
    };
    let validateTagList = (rule, value, callback) => {
      if (!this.form.tagList.length) {
        callback(new Error(this.$t('common.placeholder.selectDepartment')));
      } else {
        callback();
      }
    };
    let validateRole = (rule, value, callback) => {
      if (!this.form.role.length) {
        callback(new Error(this.$t('common.placeholder.selectRole')));
      } else {
        callback();
      }
    };
    // 验证固话手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 联系电话为空不校验
      if (!value) {
        return cb();
      }
      // 校验400开头
      const reg = /^400[0-9]{7}/;
      if (validatePhone(value, 3)) {
        return cb();
      }
      cb(new Error(this.$t('common.validate.checkTelNumber')));
    };
    const checkEmail = (rule, value, cb) => {
      if (!value || EMAIL_REG.test(value)) {
        return cb();
      }
      cb(new Error(this.$t('common.validate.checkEmail')));
    };
    let validatePass2 = (rule, value, callback) => {
      if (!value && !this.form.userId) {
        callback(new Error(this.$t('common.placeholder.inputPasswordAgain')));
      } else if (value !== this.form.pass && !this.form.userId) {
        callback(new Error(this.$t('common.validate.checkPassword')));
      } else {
        callback();
      }
    };
    return {
      isOpenData,
      action: 'create',
      higherDepartment: {},
      form: this.buildForm(),
      labelList: [],
      roles:[],
      isShowInput:false,
      originWorkNo: '', // 编辑状态下原来的工号
      rules: {
        workNo: [
          { validator: this.checkWorkNo, trigger: ['blur', 'change'] }
        ],
        displayName: [
          { required: true, message: this.$t('common.validate.inputFullName'), trigger: ['blur', 'change'] }
        ],
        loginName: [
          {
            required: true,
            validator: this.checkAccountName,
            trigger: ['blur', 'change']
          }
        ],
        accountType: [
          {
            required: true,
          }
        ],
        pass: [
          {
            required: true,
            validator: validatePass,
            trigger: ['blur', 'change']
          },
          { min: 8, message:  this.$t('common.validate.minLen', {num: '8'}), trigger: 'blur' }
        ],
        checkPass: [
          {
            required: true,
            validator: validatePass2,
            trigger: ['blur', 'change']
          },
          { min: 6, message: this.$t('common.validate.minLen', {num: '6'}), trigger: 'blur' }
        ],
        cellPhone: [
          {
            validator: checkMobile,
            trigger: ['blur', 'change']
          }
        ],
        tagList: [
          {
            required: true,
            validator: validateTagList,
            trigger: ['blur', 'change']
          }
        ],
        role: [
          {
            required: true,
            validator: validateRole,
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            required: false,
            validator: checkEmail,
            trigger: ['blur', 'change']
          }
        ],
        certificateList: [
          { required: false, message: this.$t('common.fields.skillsCertificate.placeholder'), trigger: ['input'] }
        ]
      },
      visible: true,
      isChecked: false // 更多角色复选框
    };
  },
  computed: {
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return this.initData.tenantType;
    },
    isEdit() {
      return this.action == 'edit';
    },
    roleOptions() {
      return this.roles
    },
    panelWidth() {
      return '420px';
    },
    isRole(){
      return this.keyFrom === 'role';
    },
    isService(){
      return this.keyFrom == 'serviceProvider';
    },
    // 是否有新建账号权限
    isAuthStaff(){
      return 'AUTH_STAFF' in this.initData.authorities;
    },
    // 当前账号是否存在服务商部门
    isProviderSign(){
      return sessionStorage.getItem('isProviderSign') == 1;
    },
    isWhiteList() {
      return rootWindowInitData?.WHITE_LIST
    }
  },
  created() {
    this.getBelList();
    if (this.userRow) {
      this.setForm(this.userRow);
    } else {
      this.initForm();
    }
    if(!this.isRole) {
      this.getRoleList()
    }
  },
  methods: {
     async getRoleList() {
        if(this.isService && !this.isChecked){
           await providerRole().then(r=>{
          this.roles = r.data;
       })
      }else{
        getRoleTree()
        .then(result => {
          if(!result||!result.data||!result.data.children||result.data.children.length<2){
            return false
          }
          if(result.data.children[1].type === 'assigned'){
            let roles = result.data.children[1].children;
            this.roles = roles.map(role => {
              return {
                name: role.roleName, 
                id: role.roleId,
                productLine: role.productLine,
                qualificationNames: role.qualificationNames || null,
              }
            });
          }
      })
      }
    },
    setForm(editRow) {
      this.visible = false;
      this.$nextTick(function() {
        this.visible = true;

        // 只筛选出需要用的form参数
        const Row = JSON.parse(editRow);
        this.originWorkNo = Row.workNo;
        // userId 传就是编辑，不传就是新建，staffId&department不确定是否用到，先插进去
        const DefaultForm = Object.assign(this.buildForm(), {staffId: '', userId: '', department: []})
        Object.keys(DefaultForm).forEach(key => {
          this.form[key] = Row[key] ?? ''
          if(key === 'role') {
            console.log('Row?.roles', Row?.roles)
            this.form[key] = Row?.roles ? Row?.roles.map(item => item.id) : []
          } else if( key === 'labelList') {
            this.form[key] = Row[key] ? Row[key].map(item => item.id) : []
          } else if( key === 'certificateList') {
            let certificateList = Row[key] || []

            // 解决下载时组件取的是id字段，但是接口返回的id不是fileId的问题
            certificateList.map(item=>{
              const { id,fileId } = item;
              fileId  && (item.id = fileId);
            })
            this.form[key] = certificateList
          }
        })

        // 如果角色中有除服务商的角色则请求全部角色
        if(this.isService && !this.isProviderSign){
          this.isChecked = arr.map( x => this.roles.some( v => v.id == x )).some( x => x == false )
          if(this.isChecked) this.getRoleList();
        }
      });
    },
    initForm() {
      this.visible = false;
      this.$nextTick(function() {
        this.visible = true;
        this.form = this.buildForm();
      });
    },
    roleChange(e) {
      this.form.role = e;
      this.$forceUpdate();
    },
    getBelList() {
      getBaseLabelList().then(r => {
        this.labelList = r.data;
      });
    },
    // 上传
    upload(queue) {
      this.form.certificateList = queue;
    },

    // 移除上传
    async remove(file) {
      if (!(await this.$platform.confirm(this.$t('department.createUserPanel.deleteAccessory')))) return;

      let index = -1;
      for (let i = 0; i < this.form.certificateList.length; i++) {
        let f = this.form.certificateList[i];
        if (f.url == file.url) {
          index = i;
          break;
        }
      }
      if (index >= 0) this.form.certificateList.splice(index, 1);
    },
    buildForm() {
      const form = {
        workNo: '', // 工号
        loginName: '', // 账号
        pass: '', // 密码
        checkPass: '', // 确认密码
        displayName: '', // 姓名
        accountType: 0, // 默认普通账号
        cellPhone: '', // 手机号
        email: '', // 邮箱
        role: [], // 角色
        certificateList: [], // 文件
        wechat: '', // 微信号
        labelList: [], // 标签
        tagList: [] // 部门
      };
      return form;
    },
    checkWorkNo: _.debounce(function(rule, value, callback) {
      if (value.length > 128) {
        return callback(new Error(this.$t('common.validate.employeeMaxLong')));
      }
      const { workNo } = this.form;
      // 如果工号没有变化就不需要校验
      if(this.originWorkNo != workNo) {
        userWorkNoUnique({workNo}).then(result => {
          if (result.status) {
            callback(new Error(result.message));
          } 
          callback();
        });
      } else {
        callback();
      }
    }, 1000),
    checkAccountName: _.debounce(function(rule, value, callback) {
      if(this.tenantType != 1){
         callback();
      }
      // 校验登录账号是手机号或者邮箱账号
      if (!value) {
        return callback(new Error(this.$t('common.fields.loginAccount.placeholder2')));
      } else if (!PHONE_REG.test(value) && !EMAIL_REG.test(value)) {
        return callback(new Error(this.$t('common.fields.loginAccount.placeholder3')));
      }
      
      let params = {
        loginName: this.form.loginName,
        userId: this.form.userId || ''
      };
      if (this.form.userId) {
        callback();
      }
      userLoginNameUnique(params).then(result => {
        if (result.error) {
          callback(new Error(result.error));
        } else {
          callback();
        }
      });
    }, 500),
    close() {
      // this.visible = false;
      // this.$refs.form.resetFields();
      this.initForm();
    },
    open(data) {
      this.visible = true;
    },
    packData(data) {
      this.form = this.buildForm();
      this.form.staffId = data.staffId || '';
      this.form.displayName = data.displayName || '';
      this.form.department = data.department || [];
    },
    submit() {
      this.$eventBus.$emit('submit',this.form);
      // this.initForm();
      
      if(this.$listeners.submitStart){
        this.$emit('submitStart',this.form)
      }
    },
    showInput(){
      if (!this.isWhiteList) return
      
      this.isShowInput = !this.isShowInput
    },
    validate() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let arr = [];
          for (let i of this.labelList) {
            for (let r of this.form.labelList) {
              if (i.id == r) {
                arr.push(i);
              }
            }
          }
          this.form.labelList = arr;
          this.submit();
        }
      });
    },
    // 选择部门
    update(e) {
      this.form.tagList = e;
      this.$refs['form'].clearValidate()
    },
    // 获取角色列表查询 - 用于角色管理编辑页面
    getRoleTreeByUser(){
      const { userId } = this.userRow && JSON.parse(this.userRow);
      roleGetRoleTreeByUser({ userId }).then( res => {
        if(res.status !== 0) return;
        this.roles = res.data;
      })
    },
    // 获取部门树 - 用于角色管理编辑页面
    getTagTreeByUser(e){
      const { userId } = this.userRow && JSON.parse(this.userRow);
      const { keyword, seeAllOrg, type } = e;

      let params = {
        keyword,
        seeAllOrg
      };

      if(this.isRole && this.userRow){
        params.userId = userId;
        return getTagTreeByUser(params)
      }else {
        params.type = type;
        return TeamApi.tagList(params);
      }
    },
    updatePhone(value){
      let form = this.form;
      value = phoneNumberFilter({value, type:0})
      this.$set(form, 'loginName', value);
    },
    updateCellPhone(value){
      let form = this.form;
      value = phoneNumberFilter({value, type:0})
      this.$set(form, 'cellPhone', value);
    },
  }
};
</script>

<style lang="scss">
 .add-dialog-container.service_body.add-dialog-container.service_body .el-form.demo-ruleForm{
    width: 100% !important;
  }
.create-user-panel {
  width:100%;
  box-sizing: border-box;
  padding: 0 24px;

  .create-user-form {
    overflow-y: auto;
  }
  .create-user-panel-bottom {
    padding: 0 20px;
    text-align: right;
    .base-button {
      margin-right: 20px;
    }
  }
  .el-select {
    width: 100%;
  }
}
</style>

<style lang="scss" scoped>
.label-txt {
  color: $color-warning;
}
.warning-txt {
  color: $color-warning;
  line-height: 20px;
  margin-top: 5px;
  margin-bottom: 0;
}
</style>